package com.luhuiguo.cms.server.web.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.newatlanta.appengine.vfs.provider.GaeVFS;

public class GaeDavListener implements ServletContextListener {

    public static final Logger logger = LoggerFactory.getLogger(ServletContextListener.class);

    @Override
    public void contextInitialized(ServletContextEvent event) {
        System.setProperty("appengine.server", event.getServletContext().getServerInfo());
        String userDir = System.getProperty("user.dir");

        try {
            FileObject root = GaeVFS.resolveFile("gae:///");
            if (!root.exists()) {
                root.createFolder();
            }
            FileObject templates = GaeVFS.resolveFile("gae:///templates");
            if (!templates.exists()) {
                templates.createFolder();
            }
        } catch (FileSystemException e) {
            // e.printStackTrace();
            logger.warn(e.getMessage(), e);
        }

        logger.info("Context initialized: {}", userDir);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        GaeVFS.close();
        logger.info("Context destroyed: {}", System.getProperty("user.dir"));

    }
}
